package com.lighting.module4.service.impl;

import com.lighting.module4.dto.Calculator;
import com.lighting.module4.service.CalculatorService;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.util.Locale;

/**
 * 业务逻辑类 - 等额本息
 */
@Service
public class CalculatorService0 implements CalculatorService {

    @Override
    public String[] cal(Calculator c) {
        double yr = c.getYr();
        int m = c.getM();
        double p = c.getP();

        double mr = yr / 12.0 / 100.0;        //mr为月利率
        double pow = Math.pow(1 + mr, m);
        double payment = p * mr * pow / (pow - 1);

        String[] arr = new String[]{
                NumberFormat.getCurrencyInstance(Locale.CHINA).format(payment * m),
                NumberFormat.getCurrencyInstance(Locale.CHINA).format(payment * m - p)
        };
        return arr;
    }
    @Override
    public String[][] details(Calculator c) {
        double yr = c.getYr();
        int m = c.getM();
        double p = c.getP();

        String[][] a2 = new String[m][];

        double mr = yr / 12.0 / 100.0;        //mr为月利率
        double pow = Math.pow(1 + mr, m);
        double payment = p * mr * pow / (pow - 1); //月供

        for (int i = 0; i < m; i++) {
            double payInterest = p * mr;                  //偿还利息
            double payPrincipal = payment - payInterest;  //偿还本金
            p = p - payPrincipal;                         //剩余本金

            a2[i] = CreateRow(i, payment, payPrincipal, payInterest, p);
        }
        return a2;
    }

}
